package com.demo.arthas;

import com.demo.agent.tool.ToolService;
import com.sun.tools.attach.AgentInitializationException;
import com.sun.tools.attach.AgentLoadException;
import com.sun.tools.attach.AttachNotSupportedException;
import com.sun.tools.attach.VirtualMachine;
import com.sun.tools.attach.VirtualMachineDescriptor;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.util.List;

/**
 * @author: huangjiazhen
 * @create: 2023/11/20 20:02
 * @description:
 **/
public class MyMain {
    private static int port = 9527;

    private final ToolService toolService;

    public MyMain() {
        try {
            // 加载远程服务
            this.toolService = (ToolService) Naming.lookup("rmi://localhost:" + port + "/toolService");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException, AttachNotSupportedException, AgentLoadException, AgentInitializationException {
        // 获取JVM进程列表
        List<VirtualMachineDescriptor> list = VirtualMachine.list();
        System.out.println("size: " + list.size());
        for (int i = 0; i < list.size(); i++) {
            System.out.println(String.format("[%s] %s", i, list.get(i).displayName()));
        }
        System.out.println("\n输入数字指定要attach的进程");

        // 选择jvm进程
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String line = reader.readLine();
        int num = Integer.parseInt(line);
        // 附着agent
        VirtualMachine virtualMachine = VirtualMachine.attach(list.get(num));
        virtualMachine.loadAgent("D:\\workspaces\\LearnProjects\\demo-arthas\\agent\\target\\demo-agent-1.0-SNAPSHOT.jar");
        virtualMachine.detach();
        System.out.println("加载成功！");
        // 处理命令
        MyMain main = new MyMain();
        while (true) {
            line = reader.readLine().trim();
            if ("exit".equals(line)) {
                main.toolService.exit();
                break;
            }
            main.runCmd(line);
        }
    }

    private void runCmd(String cmdAndParams) throws RemoteException {
        String[] split = cmdAndParams.split(" ");
        String cmd = split[0];
        String result = null;
        if ("sc".equals(cmd)) {
            result = toolService.findClassName(split[1]);
        } else if ("jad".equals(cmd)) {
            result = toolService.jadClass(split[1]);
        } else if ("test".equals(cmd)) {
            toolService.func(split[1]);
        } else {
            System.out.println("不支持的命令:" +cmd);
            return;
        }
        System.out.println(result);
    }
}
